// Copyright (c) 2011 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "net/http/server/comet/proxy_detect_manager.h"

#include <glog/logging.h>

#include <map>
#include <string>
#include <vector>

#include "base/init.h"
#include "net/http/server/comet/session.h"

namespace sg {
namespace net {
namespace http {
namespace server {
namespace comet {

ProxyDetectManager::ProxyDetectSet *ProxyDetectManager::proxy_detect_set_ =
    NULL;
std::mutex *ProxyDetectManager::mutex_ = NULL;

ProxyDetectManager::ProxyDetectRefCntPtr ProxyDetectManager::New(
    es::Request *req) {
  std::lock_guard<std::mutex> lock(*mutex_);
  ProxyDetectRefCntPtr rtn(new ProxyDetect(req));
  proxy_detect_set_->insert(rtn);
  return rtn;
}

void ProxyDetectManager::Remove(ProxyDetectRefCntPtr proxy_detect) {
  std::lock_guard<std::mutex> lock(*mutex_);
  proxy_detect_set_->erase(proxy_detect);
}

void ProxyDetectManager::Terminate() {
  std::lock_guard<std::mutex> lock(*mutex_);
  while (!proxy_detect_set_->empty()) {
    (*proxy_detect_set_->begin())->Stop();
  }
}

}  // namespace comet
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg

REGISTER_MODULE_INITIALIZER(
    proxy_detect_manager_initializer, {
      sg::net::http::server::comet::ProxyDetectManager::proxy_detect_set_ =
          new sg::net::http::server::comet::ProxyDetectManager::ProxyDetectSet;
      sg::net::http::server::comet::ProxyDetectManager::mutex_ =
          new std::mutex;
    })
